/**
 * Created by DevilsEyes on 2016/3/22.
 */
'use strict';

define(['text!components/payment/tmp.html', 'layer', 'pingpp', 'wx'], function (page, layer, pingpp, wx) {

    var vm = null;
    var render = template.compile(page);
    var symbol = {};
    pingpp = window.pingpp;
    var apiList = {
        getCharge: api + 'pay/charge',
        getStatus: api + 'user/poll_order_success'
    };

    vm = new Page.creat({
        $id: 'payment',
        $model: {
            $: {},
            data: {},
            payInfo: null,
            order_id: null,
            bill_id: null,
            init: function (options) {
                if (!options.order_id && options.bill_id) {
                    throw '没有获取到订单ID';
                }
                //重置数据
                symbol.show = true;
                vm.order_id = options.order_id;
                vm.bill_id = options.bill_id;
                vm.payInfo = null;

                var RenderData = {
                    close: options.close || false
                };
                var Pay_Channel = (function () {
                    if (agent.isWechat) {
                        return {
                            wx_pub: true,
                            alipay_wap: false
                        }
                    }
                    else {
                        return {
                            wx_pub: true,
                            alipay_wap: true
                        }
                    }
                })();

                RenderData = $.extend(RenderData, Pay_Channel);

                var $payment = $('#payment').html(render(RenderData));

                vm.bind$(vm.$, $payment);
                vm.bindEvent(vm.event, $payment);

                //进入动画
                {
                    var dialog = {
                        $: vm.$.payBody,
                        w: db.w - 60,
                        h: vm.$.payBody.height()
                    };
                    dialog.$.css({
                        top: (db.h - dialog.h) / 2,
                        left: (db.w - dialog.w) / 2,
                        width: dialog.w,
                        height: 0
                    });
                    vm.$.payShade.css({
                        opacity: 0
                    });
                    ex.async(function () {
                        vm.$.payShade.css({
                            opacity: 1
                        });
                        dialog.$.css({
                            height: dialog.h
                        });
                    });
                    ex.async(function () {
                        dialog.$.find('div').css({
                            opacity: 1
                        });
                    }, 200);
                }
            },
            event: {
                close: function () {

                    console.log(Page.getNowPage(), vm.order_id);
                    if (Page.getNowPage() != 'orderDetail' && vm.order_id) {
                        page_back_and_go('#/orderDetail/' + vm.order_id)
                    }

                    //防止动画冲突
                    if (symbol.close)return;
                    symbol.close = true;

                    //淡出动画
                    vm.$.payShade.css({
                        opacity: 0
                    });
                    vm.$.payBody.find('div').css({
                        opacity: 0
                    });
                    ex.async(function () {
                        vm.$.payBody.css({
                            height: 0
                        });
                    }, 100);
                    ex.async(function () {
                        $('#payment').html('');
                        symbol.close = false;
                        symbol.show = false;
                        //350ms,解决点击穿透
                    }, 350);

                },
                pay: function () {
                    var channel = $(this).attr('data-pay');
                    switch (channel) {
                        case 'wx_pub':
                            //微信 - 公众号支付
                        {
                            vm.payInfo = {
                                channel: 'wx_pub',
                                extra: {
                                    open_id: db.wx_openId
                                }
                            };
                            break;
                        }
                        case 'alipay_wap':
                            //支付宝 - 手机网页支付
                        {
                            vm.payInfo = {
                                channel: 'alipay_wap',
                                extra: {
                                    success_url: '',//todo 支付宝付款回调地址
                                    cancel_url: ''
                                }
                            };
                            break;
                        }
                    }
                    if (vm.payInfo && vm.order_id) {

                        ex.jsonp({
                            url: apiList.getCharge,
                            data: {
                                _id: vm.bill_id,
                                channel: vm.payInfo.channel,
                                extra: vm.payInfo.extra
                            },
                            success: function (obj) {

                                if (obj.code == 0) {
                                    var charge = obj.data;

                                    if (agent.isWechat) {

                                        wx.check.done(function () {
                                            pingpp.createPayment(charge, function (result, error) {
                                                if (result == "success") {
                                                    // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回，其他的 wap 支付结果都是在 extra 中对应的 URL 跳转。

                                                    ex.jsonp({
                                                        url: apiList.getStatus,
                                                        data: {
                                                            _id: vm.order_id,
                                                        },
                                                        success: function () {
                                                            vm.event.goto('#/paySuccess/message=支付成功&tips=呵呵呵&button=查看订单状态&redirect=/orderDetail/' + vm.order_id);
                                                        },
                                                        error: function (obj) {
                                                            if (obj.msg)
                                                                layer.msg(obj.msg);
                                                            else
                                                                layer.msg('还没收到渠道支付成功通知,请稍后重试,如有疑义,请联系客服');
                                                        }
                                                    });

                                                } else if (result == "fail") {
                                                    // charge 不正确或者微信公众账号支付失败时会在此处返回
                                                } else if (result == "cancel") {
                                                    // 微信公众账号支付取消支付
                                                    layer.msg('已取消,请重新支付');
                                                }
                                            });
                                        });
                                    } else {
                                        layer.msg('目前不支持微信之外访问');
                                    }

                                } else {
                                    layer.msg(obj.msg);
                                }
                            },
                            error: function (obj) {
                                if (obj.msg)
                                    layer.msg(obj.msg);
                                else
                                    layer.msg('您的网络链接不太顺畅哦');
                            }
                        })
                    }
                }
            },
            action: {}
        }
    });

    var payment = {
        start: function (options) {
            vm.init(options);
        },
        close: function () {
            if (symbol.show) {
                vm.event.close();
            }
        }
    };

    return payment;
});